<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace Sun;

class DataBase extends \PDO {

    public function __construct($db = null, $host = null, $port = null, $user = null, $pass = null) {
        parent::__construct("pgsql:dbname={$db};host={$host};port={$port}", $user, $pass);
    }

    public function TableNumRows($table, $cond) {
        $cond = $cond ? " WHERE ".$cond : "";
        $res = $this->SafeQuery("SELECT count(*) FROM \"{$table}\" {$cond}")
            ->fetch(DataBase::FETCH_NUM);
        return $res[0];
    }

    public function QueryNumRows($query) {
        $res = $this->SafeQuery("SELECT count(*) FROM ({$query}) M")
            ->fetch(DataBase::FETCH_NUM);
        return $res[0];
    }

    public static function FetchData($res, $offset = 0, $count = 1, $type = DataBase::FETCH_ASSOC) {
        $array = array();
        $val = $res->fetch($type, DataBase::FETCH_ORI_NEXT, 100);
        if ($val) $array[] = $val;
        for ($i = 1; $i < $count; ++$i) {
            if (!($val = $res->fetch($type))) break;
            else $array[] = $val;
        }
        return $array;
    }

    public static function FetchFields($res, $attr = "name") {
        $names = array();
        for ($i = 0; $i < $res->columnCount(); ++$i) {
             $col= $res->getColumnMeta($i);
             $names[] = $col['name'];
        }
        return $names;
    }

    public function SafeQuery($query) {
        $res = $this->query($query);
        if (!$res) {
            $msg = $this->errorInfo();
            throw new \Sun\Exceptions\DBException($msg[2], $msg[1]);
        }
        else return $res;
    }

    public function SafeExec($query) {
        $res = $this->exec($query);
        if ($res === false) {
            $msg = $this->errorInfo();
            throw new \Sun\Exceptions\DBException($msg[2], $msg[1]);
        }
        else return $res;
    }

    public function Table($name, $fields = "*", $cond = "") {
        $query = "SELECT {$fields} FROM \"$name\" ".$cond;
        return $this->SafeQuery($query);
    }

}
